<?php 
// +----------------------------------------------------------------------
// | CRMUU-企微SCRM是专业的企业微信第三方源码系统.
// +----------------------------------------------------------------------
// | [CRMUU] Copyright (c) 2022 http://crmuu.com All rights reserved.
// +----------------------------------------------------------------------

namespace app\wework\model\user\sop;
use think\facade\Db;
use think\facade\Session;
use app\wework\model\QyWechatApi;

/**
* 群sop类
**/
class GroupSopModel {
	static public $wid;
	/**
	 * 获取用户列表数据
	 * @param $wid 账户id
	 * @param $data 接受的数据
	 * @return 
	 */
	static public function list($req){
		$wid = Session::get('wid');
		$page = $req->post('page',1);
		$size = $req->post('size',10);
		$name = $req->post('name');
		$res = Db::table('kt_wework_groupsop')
			   ->field('id,wid,groupid,group_condition_tag,status,group_type,group_condition_type,name,send_type,group_condition_new,group_condition_new_start,group_condition_new_end,create_time')
			   ->json(['groupid',"group_condition_tag"])
			   ->where('wid',$wid);
		if($name) $res->whereLike('name',"%$name%");
		$data['count'] = $res->count();
		$data['item'] = $res ->page($page,$size)
			->filter(function($r){
				$r['group_number'] = count(self::selectGroup($r));
				return $r;
			})
			->select();
		$data['page'] = $page;
		$data['size'] = $size;
		return success('群sop',$data);
	}
	/**
	 * 查看符合条件的群聊
	 */
	static public function selectGroup($data){
		$wid = $data['wid'];
		if($data['group_type'] == 1) return $data['groupid'];
		if($data['group_condition_type'] == 1){
			$tags = $data['group_condition_tag'];
			$res = Db::table("kt_wework_group");
			foreach ($tags as $value){
				$where = [];
	            $where[0] = ["wid","=",$wid];
	            $where[0] = ["tags","like","%{$value}%"];
				$res = $res->whereOr($where);
			}
			$res = $res->select()->toArray();
		}
		$chat = [];
		if($data['group_condition_type'] == 2){
			if($data['group_condition_new'] == 1){
				$chat = Db::table('kt_wework_group')->where('wid',$wid)->whereTime('create_time',">=",$data['group_condition_new_start'])->select()->toArray();
			}
			if($data['group_condition_new'] == 2){
				$chat = Db::table('kt_wework_group')->where('wid',$wid)->whereTime('create_time',"between",[$data['group_condition_new_start'],$data['group_condition_new_end']])->select()->toArray();
			}
			
		}
		
		return $chat;
	}

	/**
	 * 获取详情
	 * @param $wid 账户id
	 * @param $data 接受的数据
	 * @return 
	 */
	static public function detail($req){
		$wid = Session::get('wid');
		$id = $req->post('id');
		$res = Db::table('kt_wework_groupsop')->json(['groupid','group_condition_tag'])->find($id);
		if($res["groupid"])$res["group_list"] = Db::table("kt_wework_group")->where(["chat_id"=>$res["groupid"]])->field("name,chat_id")->select()->toArray();
		if($res["group_condition_tag"])$res["group_condition_tag_list"] = Db::table("kt_wework_group_tag")->where(["id"=>$res["group_condition_tag"]])->field("name,id")->select()->toArray();
		$res["send_content"] = Db::table("kt_wework_groupsop_detail")
									->where(["pid"=>$res["id"]])
									->json(["content"])
									->filter(function($send) use($wid){
										$send["y_send"] = Db::table("kt_wework_groupsop_time")
										->where(["pid"=>$send["pid"],"detail_id"=>$send["id"],"type"=>1])
										->filter(function($group) use($wid){
											$groups = Db::table("kt_wework_group")->where(["wid"=>$wid,"chat_id"=>$group["group_id"]])->find();
											$group["group_name"] = $groups["name"];
											$staff = Db::table("kt_wework_staff")->where(["wid"=>$wid,"id"=>$groups["staff_id"]])->find();
											$group["staff_name"] = $staff["name"];
											return $group;
										})
										->select()
										->toArray();
										$send["y_send_size"] = count($send["y_send"]);
										$send["n_send"] = Db::table("kt_wework_groupsop_time")
										->where(["pid"=>$send["pid"],"detail_id"=>$send["id"],"type"=>0])
										->filter(function($group) use($wid){
											$groups = Db::table("kt_wework_group")->where(["wid"=>$wid,"chat_id"=>$group["group_id"]])->find();
											$group["group_name"] = $groups["name"];
											$staff = Db::table("kt_wework_staff")->where(["wid"=>$wid,"id"=>$groups["staff_id"]])->find();
											$group["staff_name"] = $staff["name"];
											return $group;
										})
										->select()
										->toArray();
										$send["n_send_size"] = count($send["n_send"]);
										return $send;
									})
									->select()
									->toArray();
		return success('群sop详情',$res);
	}
	/**
	 * 删除
	 * @param $wid 账户id
	 * @param $data 接受的数据
	 * @return 
	 */
	static public function delete($req){
		$wid = Session::get('wid');
		$id = $req->post('id');
		$res = Db::table('kt_wework_groupsop')->delete($id);		   
		return success('群sop删除成功');
	}
	/**
	 * 开关
	 * @param $wid 账户id
	 * @return 
	 */
	static public function open($req){
		$wid = Session::get('wid');
		$id = $req->post('id');
		if(!$id) return error('参数错误');
		$status = $req->post('status',0);
		$res = Db::table('kt_wework_groupsop')->where('id',$id)->update([
			'status' => $status
		]);
		return success('操作成功');
	}
	/**
	 * 添加
	 * @param $wid 账户id
	 * @param $data 接受的数据
	 * @return 
	 */
	static public function add($req){
		$wid = Session::get('wid');
		$data = [];
		$data['wid'] = $wid;
		$data['name'] = $req->post('name');
		if(!$data['name']) return error('缺少参数name');
		$data['group_type'] = $req->post('group_type',1);
		$data['groupid'] = $req->post('groupid',[]);
		$data['group_condition_type'] = $req->post('group_condition_type',1);
		$data['group_condition_tag'] = $req->post('group_condition_tag',[]);
		$data['group_condition_new'] = $req->post('group_condition_new',1);
		$data['group_condition_new_start'] = $req->post('group_condition_new_start');
		$data['group_condition_new_end'] = $req->post('group_condition_new_end');
		if($data['group_type'] == 1 && !$data['groupid']) return error('请选择群聊');
		if($data['group_type'] == 2 && $data['group_condition_type'] == 1 && !$data['group_condition_tag']) return error('请选择标签');
		if($data['group_type'] == 2 && $data['group_condition_type'] == 2 ){
			if(!$data['group_condition_new_start']) return error('请输入开始时间');
			if($data['group_condition_new'] == 2 && !$data['group_condition_new_end'] ) return error('请输入结束时间');
			if($data['group_condition_new'] == 2){
				$data['group_condition_new_start'] = $group_condition_new_end[0];
				$data['group_condition_new_end'] = $group_condition_new_end[1];
			}
		} 
		$data['send_type'] = $req->post('send_type',1);
		$data['send_starttime_type'] = $req->post('send_starttime_type',1);
		$data['send_starttime'] = $req->post('send_starttime');
		$data['send_endtime_type'] = $req->post('send_endtime_type',1);
		$data['send_endtime_date'] = $req->post('send_endtime_date');
		$data['send_endtime_time'] = $req->post('send_endtime_time');
		$data['send_endtime_size'] = $req->post('send_endtime_size');
		$data['send_endtime_date_type'] = $req->post('send_endtime_date_type');
		if($data['send_type'] == 2){
			if($data['send_starttime_type'] == 1)  $data['send_starttime'] = date("Y-m-d H:i:s");
			if($data['send_starttime_type'] == 2 && !$data['send_starttime']) error('请输入周期推送开始时间');
			if($data['send_endtime_type'] = 2 && (!$data['send_endtime_date'] || !$data['send_endtime_time'])) error('请输入周期推送结束时间');
			if($data['send_endtime_type'] = 3 && !$data['send_endtime_date_type'] && !$data['send_endtime_size']) error('请输入周期推送结束时间');
			if($data['send_starttime_type'] == 2  && $data['send_starttime'] > date("Y-m-d H:i:s"))$data["status"] = 2;
		}
		$send_content = $req->post('send_content',[]);
		if(!$send_content) return error('请添加规则');
		$data['update_time'] = date("Y-m-d H:i:s");
		if($req->post('id')){
			$id = $req->post('id');
			$data['id'] = $req->post('id');
			$res = Db::table('kt_wework_groupsop')->json(['groupid','group_condition_tag'])->save($data);	 
		} else {
			$data['create_time'] = date("Y-m-d H:i:s");
			$res = Db::table('kt_wework_groupsop')->json(['groupid','group_condition_tag'])->insertGetId($data);	
			$id = $res;
		}
		if($req->post("del_content"))Db::table("kt_wework_groupsop_detail")->delete($req->post("del_content"));
		$group_list = Db::table("kt_wework_group");
		if($req->post("group_type") == 2){
			if($req->post["group_condition_type"] == 1){
				foreach ($req->post["group_condition_tag"] as $tag){
					$where = [];
            		$where[] = ["tags","like","%$tag%"];
            		$group_list = $group_list->whereOr($where);
				}
     		$group_list = $group_list->where(["wid"=>$wid])->field("id,name,chat_id")->select()->toArray();
			}else{
				if($req->post["group_condition_new"] == 1)$group_list = $group_list->where(["wid"=>$wid])->whereTime('create_time','>=',$req->post["group_condition_new_start"])->field("id,name,chat_id")->select()->toArray();
				if($req->post["group_condition_new"] == 2)$group_list = $group_list->where(["wid"=>$wid])->whereBetweenTime('create_time',$req->post["group_condition_new_start"],$req->post["group_condition_new_end"])->field("id,name,chat_id")->select()->toArray();
			}
		}else{
			$group_list = $group_list->where(["wid"=>$wid,"chat_id"=>$req->post("groupid")])->field("id,name,chat_id")->select()->toArray();
		}
		foreach ($send_content as $content){
			$datas["wid"] = $wid;
			$datas["pid"] = $id;
			$datas["content"] = json_encode($content["content"],320);
			$datas["name"] = $content["name"];
			$datas["type"] = $content["type"];
			if($content["type"] == 3){
				$datas["hour"] = $content["hour"];
			}
			$datas["size"] = $content["size"];
			$datas["time"] = $content["time"];
			if(isset($content["id"])){
				$detail_id = $content["id"];
				Db::table("kt_wework_groupsop_detail")->where(["id"=>$content["id"]])->save($datas);
			}
			if(!isset($content["id"]))$detail_id = Db::table("kt_wework_groupsop_detail")->insertGetId($datas);
			foreach ($group_list as $group){
				$is_set = Db::table("kt_wework_groupsop_time")->where(["pid"=>$id,"group_id"=>$group["chat_id"],"detail_id"=>$detail_id])->find();
				if(!$is_set){
					$time["pid"] = $id;
					$time["detail_id"] = $detail_id;
					$time["group_id"] = $group["chat_id"];
					$time["ctime"] = date("Y-m-d H:i:s");
					Db::table("kt_wework_groupsop_time")->insertGetId($time);
				}
			}
		}
		if($res) return success('更新群sop成功');
		return error('更新群sop失败');
	}

	static public function size($tags){
		$wid = Session::get('wid');
		$res = Db::table("kt_wework_group");
		foreach ($tags as $value){
			$where = [];
            $where[] = ["tags","like","%{$value}%"];
			$res = $res->whereOr($where);
		}
		$res = $res->where(["wid"=>$wid])->count();

		return $res;
	}

	static public function sizes($ktime,$times=NULL){
		$wid = Session::get('wid');
		if(!$times)$res = Db::table("kt_wework_group")->where(["wid"=>$wid])->whereTime('create_time','>=', $ktime)->count();
		if($times)$res = Db::table("kt_wework_group")->where(["wid"=>$wid])->whereTime('create_time', 'between', [$times[0], $times[1]])->count();

		return $res;
	}
}
